#  fromxyz v 0.1 - Converts from a text xyz file to a TPQ image.
#  Copyright (C) 2010 John Donovan - mersey.viking@gmail.com

#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at

#  http://www.apache.org/licenses/LICENSE-2.0

#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import numpy
import numpy.ma
import math

import image

def fromxyz(source_filename, tile_shape=(20, 20), no_data=2047.5):
    if tile_shape[0] == 0 or tile_shape[1] == 0:
        raise ValueError

    # Load the data and rotate the array so that there are three columns.
    samples = numpy.loadtxt(source_filename, unpack=True).swapaxes(0, 1)
    
    # Gracefully exit if we have negative indices.
    if numpy.amin(samples, axis=0)[0] < 0 or numpy.amin(samples, axis=0)[1] < 0:
        raise IndexError
        
    # Extend up to an integer number of tiles in each axis.
    tile_xcount = math.ceil((numpy.amax(samples, axis=0)[0] + 1) / tile_shape[0])
    tile_ycount = math.ceil((numpy.amax(samples, axis=0)[1] + 1) / tile_shape[1])
    xmax = tile_xcount * tile_shape[0]
    ymax = tile_ycount * tile_shape[1]

    # We may end up with parts of the image not touched by the xyz file, so
    # initialize it to the no_data value first.
    img = image.Image(numpy.ma.empty((ymax, xmax)), tile_shape)
    img.fill_value = no_data
    img.fill(no_data)

    for sample in samples:
        img[sample[1], sample[0]] = sample[2]

    img.mask = numpy.ma.make_mask(img == no_data)

    return img
